package com.dididoctor.doctor.WYY;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.dididoctor.doctor.Activity.GlobalParams;
import com.dididoctor.doctor.Utils.ABFileUtil;
import com.dididoctor.doctor.Utils.PhotoHelper;
import com.netease.nim.uikit.session.actions.BaseAction;
import com.netease.nim.uikit.session.constant.RequestCode;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.io.File;

/**
 * Created by hzxuwen on 2015/6/11.
 */
public class SendImageAction extends BaseAction {
    private int code;
    private PhotoHelper mPhotoHelper;
    private String capturePath = null;
    private Activity activity;

    public SendImageAction(int code) {
        super(code == RequestCode.PICTURE ? com.netease.nim.uikit.R.drawable.nim_message_plus_photo_selector : com.netease.nim.uikit.R.drawable.nim_message_plus_video_selector,
                code == RequestCode.PICTURE ? com.netease.nim.uikit.R.string.picture : com.netease.nim.uikit.R.string.takepicture);
        this.code = code;
        this.capturePath = ABFileUtil.getAppTmpPath() + "/TMP.jpg";
        Context context = GlobalParams.getContext();
        activity = (Activity) context;
        mPhotoHelper = new PhotoHelper(activity, capturePath);
    }

    @Override
    public void onClick() {
        if (RequestCode.PICTURE == code) {
            mPhotoHelper.takePictureFromAlbum();
        } else if (RequestCode.TACK_PICTUCE == code) {
            mPhotoHelper.takePhoto();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mPhotoHelper.TO_CAMEIA && resultCode == activity.RESULT_OK) {//来自系统相机的返回
            mPhotoHelper.startPhotoZoom(Uri.fromFile(new File(capturePath)));
        } else if (requestCode == mPhotoHelper.TO_PHOTO && resultCode == activity.RESULT_OK && data != null) {//来自系统相册的返回
            Uri uri = data.getData();
            mPhotoHelper.startPhotoZoom(uri);
        } else if (requestCode == mPhotoHelper.TO_ZOOM_PHOTO && data != null) {//裁剪完成后

            // 创建图片消息
            IMMessage message = MessageBuilder.createImageMessage(
                    "", // 聊天对象的 ID，如果是单聊，为用户帐号，如果是群聊，为群组 ID
                    SessionTypeEnum.P2P, // 聊天类型，单聊或群组
                    new File(capturePath), // 图片文件对象
                    null // 文件显示名字，如果第三方 APP 不关注，可以为 null
            );
            NIMClient.getService(MsgService.class).sendMessage(message, false);
        }
    }
}
